//
//  kata_StopViewController.m
//  CityStar
//
//  Created by wangjia on 14-7-12.
//  Copyright (c) 2014年 kata. All rights reserved.
//

#import "kata_StopViewController.h"
#import "kata_StopCell.h"
#import "HTDefine.h"
#import "INTULocationManager.h"
#import "HttpRequestManager.h"
#import "KInterFace.h"
#import "SVProgressHUD.h"
#import "kata_OKInfoViewController.h"

@interface kata_StopViewController ()<CLLocationManagerDelegate>

@property (retain, nonatomic) CLLocationManager *locManager;
@property (nonatomic, assign) CLLocationCoordinate2D loc;
@property (nonatomic, strong) NSArray *requestArray;
@property (nonatomic, strong) UILabel *labelNoParking;
@property (nonatomic, strong) ParkMessage *parkMessage;
@property (nonatomic, strong) NSString *parkUUID;
@end

@implementation kata_StopViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.sectionFooterHeight = 0;
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.backgroundColor = rgba(246, 245, 241, 1);
    
    UIButton * regBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    regBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [regBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [[regBtn titleLabel] setFont:[UIFont systemFontOfSize:15]];
    [regBtn setTitle:@"信息" forState:UIControlStateNormal];
    [regBtn setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:regBtn];
    [regBtn addTarget:self action:@selector(infoAction) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.intID == 4218) {
        self.title = @"停车";
    }else if (self.intID == 4217){
        self.title = @"代驾";
    }
    
    self.requestArray = [[NSArray alloc]init];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 90, 30)];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setFrame:CGRectMake(-30, 0, 90, 30)];
    [leftButton setTitle:@"返回" forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [leftButton setTitleColor:[UIColor colorWithWhite:0.200 alpha:1.000] forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor colorWithRed:0.991 green:0.532 blue:0.303 alpha:1.000] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftButton setImage:[UIImage imageNamed:@"back_touch"] forState:UIControlStateHighlighted];
    
    [view addSubview:leftButton];
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:view];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    
    
    self.labelNoParking = [[UILabel alloc]init];
    self.labelNoParking.userInteractionEnabled = YES;
    self.labelNoParking.frame = CGRectMake(self.view.bounds.origin.x, 300, self.view.bounds.size.width, 30);
    self.labelNoParking.textAlignment = NSTextAlignmentCenter;
    self.labelNoParking.textColor = [UIColor colorWithWhite:0.769 alpha:1.000];
    self.labelNoParking.text = @"您的附近暂无停车场";
    self.labelNoParking.hidden = YES;
    [self.view addSubview:self.labelNoParking];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    //初始化位置管理器
    self.locManager = [[CLLocationManager alloc]init];
    //设置代理
    self.locManager.delegate = self;
    //设置位置经度
    self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置每隔100米更新位置
    self.locManager.distanceFilter = 100;
    //开始定位服务
    [self.locManager startUpdatingLocation];
}

-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >=7.0) {
        self.navigationController.navigationBar.translucent = NO; //禁止半透明毛玻璃效果
        self.navigationController.navigationBar.tintColor = kWhiteNavTitleColor; //返回按钮颜色
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor]; //bar背景颜色
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]}; //标题颜色
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }else{
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]]; //bar背景颜色
        self.navigationController.navigationBar.translucent = NO;
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:kWhiteNavTitleColor,NSFontAttributeName:[UIFont boldSystemFontOfSize:18]};
        self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - LocationDelegate
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

//协议中的方法，作用是每当位置发生更新时会调用的委托方法
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    self.loc = [newLocation coordinate];
    [self webRequest_getParkMessage];
    
    //    float longitude = loc.longitude;
    //    float latitude = loc.latitude;
    
    //    CLLocation *commodityLocation = [[CLLocation alloc]initWithLatitude:[self.merchantDetail.latitude doubleValue]/10000000 longitude:[self.merchantDetail.longtitude doubleValue]/10000000];
    //    CLLocation *currentLocation = [[CLLocation alloc]initWithLatitude:loc.latitude longitude:loc.longitude];;
    //    CLLocationDistance kilometers=[commodityLocation distanceFromLocation:currentLocation]/1000;
    //    DLog(@"%f",kilometers);
    //    self.cityDistance = [NSString stringWithFormat:@"%.0f",kilometers*10000];
    
}

#pragma mark - WebRequest
-(void)webRequest_getParkMessage
{
    
    NSString *postUrl = [NSString stringWithFormat:@"%@latitude/%lf/longtitude/%lf",KInterface_GetDriverQuery,self.loc.latitude,self.loc.longitude];
    [HttpRequestManager getMethod:postUrl parameters:nil completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        NSLog(@"%@",response);
        if (success) {
            self.requestArray = response[@"value"][@"content"];
            if (self.requestArray.count > 0) {
                self.labelNoParking.hidden = YES;
            }else{
                self.labelNoParking.hidden = NO;
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showErrorWithStatus:errMsg];
        }
    }];
}

#pragma mark - tableViewDelegate and DateSource
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.requestArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *inviteCellIdentifier = @"stopCell";
    static NSString *daiCellIdentifier = @"daiCell";
    
    kata_StopCell *cell = nil;
    if (self.intID == 4218) {
        cell = (kata_StopCell *)[tableView dequeueReusableCellWithIdentifier:daiCellIdentifier];
    }else if (self.intID == 4217){
        cell = (kata_StopCell *)[tableView dequeueReusableCellWithIdentifier:inviteCellIdentifier];
    }
    
    if (cell == nil) {
        cell = [[kata_StopCell alloc]init];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    int i = 0;
    if (self.intID == 4218) {
        i = 0;
    }else if (self.intID == 4217){
        i = 1;
    }
    if (self.intID == 4218) {
        ParkMessage *parkMessage = [ParkMessage objectFromDictionary:self.requestArray[indexPath.row]];
        [cell setValueWithData:i count:[parkMessage.last intValue]];
        [cell configWithMessage:parkMessage];
        if ([parkMessage.last intValue] == 0) {
        }else{
            cell.btnStop.tag = indexPath.row;
            [cell.btnStop addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    

    if (!cell.btnCall.hidden) {
        [cell.btnCall addTarget:self action:@selector(connectAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView reloadData];
}


- (void)infoAction{
    [self performSegueWithIdentifier:@"segInfo" sender:nil];
}

- (IBAction)stopAction:(UIButton *)sender{
    if (self.intID == 4218) {
        if ([[NSUserDefaults standardUserDefaults]objectForKey:@"parkCarID"]) {
            self.parkMessage = [ParkMessage objectFromDictionary:self.requestArray[sender.tag]];
            
            NSString * uuid = [[NSUUID UUID]UUIDString];
            NSDictionary *parameters = @{@"uuid":uuid,
                                         @"park":self.parkMessage.objectId,
                                         @"car":[[NSUserDefaults standardUserDefaults]objectForKey:@"parkCarName"],
                                         @"mobile":[[NSUserDefaults standardUserDefaults]objectForKey:@"parkCarPhone"],
                                         @"driver":[[NSUserDefaults standardUserDefaults]objectForKey:@"parkCarID"],
                                         };
            [HttpRequestManager postMethod:KinterFace_driverOrder parameters:parameters completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
                if (success) {
                    NSLog(@"%@",response);
                    self.parkUUID = response[@"value"];
                    [self performSegueWithIdentifier:@"segOKInfo" sender:nil];
                }else{
                    [SVProgressHUD showErrorWithStatus:errMsg];
                }
            }];
        }else{
            [self performSegueWithIdentifier:@"segInfo" sender:nil];
//            [SVProgressHUD showErrorWithStatus:@"请添加停车信息"];
        }

    }
    else if (self.intID == 4217){
        [self performSegueWithIdentifier:@"segOKDrive" sender:nil];
    }
    
}

- (IBAction)connectAction:(id)sender {
    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"是否联系司机" message:@"182-2906-2533" delegate:self cancelButtonTitle:nil otherButtonTitles:@"拨号",@"取消", nil];
    av.tag = 1;
    [av show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (alertView.tag == 1) {
        if (buttonIndex == 0) {
            NSString *phone = @"182-2906-2533";
            NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
            NSURL *url = [[NSURL alloc] initWithString:telUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[NSUserDefaults standardUserDefaults]objectForKey:@"parkCarID"]) {
        kata_OKInfoViewController *okInfoVC = segue.destinationViewController;
        NSDictionary *dict = @{@"name":self.parkMessage.name,
                               @"price":[NSString stringWithFormat:@"%@",self.parkMessage.price],
                               @"uuid":self.parkUUID};
        [okInfoVC setMessage:dict];
    }
}

@end
